<template>
  <el-dialog
    ref="dragDialog"
    v-el-drag-dialog="{minWidth: 750, resize: resize, updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    class="port-edit"
    :width="setDialogWidth(rowData.nodeCategory === 'LIGHT_SPLIT' ? '600px' : '1200px')"
    :visible="visible"
    :title="rowData.nodeName+$t('PORT')"
    @close="close"
    @open="open"
  >
    <div v-if="rowData.nodeCategory !== 'LIGHT_SPLIT'" class="node-name flex">
      <div v-if="rowData.nodeCategory === 'ODF'" class="flex align-center">
        <el-checkbox v-model="checkAll" @change="handleCheckAllChange">{{ $t('SELECT_ALL_CHECK') }}</el-checkbox>
        <div v-if="checkedMore.length > 0" class="flex align-center ml-20">
          <span style="width:180px;">{{ $t('BATCHSETINSTALLATION_STATUS') }}:</span>
          <el-select v-model="installed" class="select">
            <el-option :label="$t('INSTALLED')" :value="true" />
            <el-option :label="$t('UNINSTALLED')" :value="false" />
          </el-select>
        </div>
      </div>
      <div v-if="showExportBtn" class="flex align-center ml-auto">
        <el-button
          v-if="rowData.nodeCategory !== 'SPLICE_CLOSURE'"
          slot="trigger"
          class="ml-10"
          size="mini"
          type="primary"
          @click="importVisible = true"
        >{{ $t("IMPORT") }}</el-button>
        <el-button class="ml-10" size="mini" @click="exportClick">
          {{ $t("EXPORT") }}
        </el-button>
      </div>
    </div>
    <div v-if="cloneDetailData" class="overflow-auto relative nodeportbox">
      <port-shelf
        v-if="rowData.nodeCategory === 'TRANSPORT'"
        :clone-detail-data="cloneDetailData"
      />
      <port-light-split
        v-if="rowData.nodeCategory === 'LIGHT_SPLIT'"
        :clone-detail-data="properties"
      />
      <port-flange
        v-if="rowData.nodeCategory === 'ODF'"
        ref="portFlange"
        :installed="installed"
        :check-all="checkAll"
        :clone-detail-data="cloneDetailData"
        @changecheckAll="checkAll = false"
        @changeCheckedMore="changeCheckedMore"
      />

      <port-afs v-if="rowData.nodeType === 'AFS'" :clone-detail-data="cloneDetailData" />
      <port-cluster
        v-if="rowData.nodeCategory === 'AFS' && rowData.nodeType !== 'AFS'"
        :clone-detail-data="cloneDetailData"
      />
      <!--接头盒-->
      <JointBox
        v-if="rowData.nodeType === 'SPLICE_CLOSURE'"
        id="jointable"
        :splice-port-list="splicePortList"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ $t("CANCEL") }}</el-button>
      <el-button type="primary" @click="savePort">{{ $t("CONFIRM") }}</el-button>
    </div>
    <!--导入引导-->
    <import-boot
      :visible="importVisible"
      @ImportClick="importClick"
      @import-close="importVisible = false"
    >
      <template #notice>
        {{ $t("BEFORE_IMPORTING_PLEASE") }}
        <span class="exportClick" @click="exportClick">
          {{ $t("EXPORT_TEMPLATE") }}
        </span>
        {{ $t("ALL_PORT_INFORMATION") }}
      </template>
    </import-boot>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { importExcel, exportExcel } from '@/utils/jsonToExcel'
  import PortAfs from './port/Afs'
  import PortCluster from './port/Cluster'
  import PortFlange from './port/Flange'
  import JointBox from './port/SpliceClosure'
  import PortLightSplit from './port/LightSplit'
  import PortShelf from './port/Shelf'
  import nodeApi from '@/api/oen/NodeApi'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  import ImportBoot from '@/components/ImportBoot'
  import { tableToExcel } from '@/utils/jsonToExcel'
  import { deepClone } from '@/utils/common'

  export default {
    name: 'NodePorts',
    components: {
      PortAfs,
      PortFlange,
      PortLightSplit,
      PortShelf,
      ImportBoot,
      PortCluster,
      JointBox
    },
    props: {
      visible: { type: Boolean, default: false },
      type: { type: String, default: '' },
      rowData: { type: Object, default: () => {} }
    },
    data() {
      return {
        baseData: {},
        cloneDetailData: null,
        importVisible: false,
        splicePortList: [], // 接头盒端口列表
        installed: '',
        checkedMore: [],
        checkAll: false
      }
    },
    computed: {
      properties() {
        return this.rowData.properties
      },
      spliceClosure() {
        return this.properties.spliceClosure
      },
      inputList() {
        return this.spliceClosure.inputList
      },
      outputList() {
        return this.spliceClosure.outputList
      },
      showExportBtn() {
        // 判断是否显示导入导出按钮
        if (
          this.rowData.nodeCategory === 'AFS' &&
          this.rowData.properties.afsInfo &&
          this.rowData.properties.afsInfo.faceList.length !== 0
        ) {
          return true
        } else if (this.rowData.nodeCategory === 'ODF' && this.rowData.properties.odf) {
          return true
        } else if (
          this.rowData.nodeCategory === 'TRANSPORT' &&
          this.rowData.properties.trans
        ) {
          return true
        } else if (this.rowData.nodeCategory === 'SPLICE_CLOSURE') {
          return true
        } else {
          return false
        }
      },
      ...mapGetters(['getUserId', 'getUser'])
    },
    watch: {
      visible: {
        handler() {
          if (this.rowData.nodeCategory === 'ODF') {
            this.properties.odf.faceList.forEach((i) => {
              i.holeList[0].faceName = i.faceName
            })
          }
          this.cloneDetailData = this.properties
          this.baseData = deepClone(this.properties)
        },
        immediate: true
      }
    },
    methods: {
      handleCheckAllChange(val) {
        this.$refs.portFlange.handleCheckAllChange(val)
      },
      changeCheckedMore(data) {
        this.checkedMore = data
      },
      portList() {
        // 获取节点下接头盒的端口列表状态
        const list = this.spliceClosure.splicePortInfoList
        const inputIds = list.map((i) => i.inputSplicePortId)
        const outputIds = list.map((i) => i.outputSplicePortId)
        nodeApi
          .portList({ nodeId: this.rowData.nodeId, portIds: [...inputIds, ...outputIds] })
          .then((res) => {
            const statusList = res || []
            // 把端口状态赋值给进出端口列表项
            list.forEach((item) => {
              const inputObj = statusList.find(
                (port) => item.inputSplicePortId === port.portId
              )
              const outputObj = statusList.find(
                (port) => item.outputSplicePortId === port.portId
              )
              item.inputPortName = inputObj.portName
              item.outputPortName = outputObj.portName
              const isDisabled =
                inputObj &&
                inputObj.status === 'IDLE' &&
                outputObj &&
                outputObj.status === 'IDLE'
              item.inputStatus = isDisabled ? 'IDLE' : 'conne'
              item.outputStatus = isDisabled ? 'IDLE' : 'conne'

              const iObj = this.inputList.find((i) => i.spliceId === item.inputSpliceId)
              if (iObj) {
                item.inputName = iObj.spliceName
              }
              const oObj = this.outputList.find((i) => i.spliceId === item.outputSpliceId)
              if (oObj) {
                item.outputName = oObj.spliceName
              }
            })
            this.saveSplicePortInfoList = list.sort((a, b) => a.sort - b.sort)
            this.splicePortList = deepClone(this.saveSplicePortInfoList)
          // console.log('list-------', list)
          })
      },
      open() {
        if (this.rowData.nodeType === 'SPLICE_CLOSURE') {
          this.portList()
        }
      },
      savePort() {
        const postData = {
          nodeId: this.rowData.nodeId,
          nodeCategory: this.rowData.nodeCategory
        }
        // console.log(this.baseData, this.properties)
        // 接头盒
        if (this.rowData.nodeType === 'SPLICE_CLOSURE') {
          const portInfoList = []
          const oldList = this.saveSplicePortInfoList
          const newList = this.splicePortList
          oldList.forEach((i) => {
            const inObj = newList.find((j) => j.inputSplicePortId === i.inputSplicePortId)
            if (inObj && inObj.inputPortName !== i.inputPortName) {
              portInfoList.push({
                portId: inObj.inputSplicePortId,
                portName: inObj.inputPortName
              })
            }
            const outObj = newList.find(
              (j) => j.outputSplicePortId === i.outputSplicePortId
            )
            if (outObj && outObj.outputPortName !== i.outputPortName) {
              portInfoList.push({
                portId: outObj.outputSplicePortId,
                portName: outObj.outputPortName
              })
            }
          })
          // console.log('portInfoList--------', portInfoList)
          nodeApi.updateBatch(portInfoList).then((res) => {
            this.$message.success(this.$t('MODIFY_SUCCESS'))
            this.close(true)
          })
          return
        }
        // odf设备差量
        if (this.rowData.nodeCategory === 'ODF') {
          postData.odfList = []
          const odfList = []
          const oldList = this.baseData.odf.faceList
          const newList = this.cloneDetailData.odf.faceList
          newList.forEach((face, i) => {
            const faceItem = {
              faceId: face.faceId
            }
            faceItem.holeList = face.holeList.filter(
              (hole, j) =>
                hole.holeName !== oldList[i].holeList[j].holeName ||
                hole.installed !== oldList[i].holeList[j].installed
            )
            if (faceItem.holeList.length > 0) {
              odfList.push(faceItem)
            }
          })
          // 名称必填校验
          if (
            odfList.some((i) => i.holeList.some((j) => String(j.holeName).trim() === ''))
          ) {
            this.$message.error(
              this.$t('MSG_NOT_EMPTY', {
                msg: this.$t('PORT_NAME')
              })
            )
            return
          }
          odfList.forEach((i) => {
            i.holeList.forEach((j) => {
              postData.odfList.push({
                holeId: j.holeId,
                holeName: j.holeName,
                installed: j.installed
              })
            })
          })
        }
        // 传输设备差量
        if (this.rowData.nodeCategory === 'TRANSPORT') {
          postData.transList = []
          const oldList = [...this.baseData.trans.shelfList]
          const newList = [...this.cloneDetailData.trans.shelfList]
          newList.forEach((shelf, i) => {
            shelf.slotList.forEach((slot, j) => {
              slot.netPortList.forEach((netPort, z) => {
                netPort.portList.forEach((port, x) => {
                  if (
                    port.bizName !==
                    oldList[i].slotList[j].netPortList[z].portList[x].bizName ||
                    port.resourceCode !==
                    oldList[i].slotList[j].netPortList[z].portList[x].resourceCode
                  ) {
                    postData.transList.push(port)
                  }
                })
              })
            })
          })
          // 名称必填校验
          if (postData.transList.some((i) => String(i.bizName).trim() === '')) {
            this.$message.error(
              this.$t('MSG_NOT_EMPTY', {
                msg: this.$t('PORT_NAME')
              })
            )
            return
          }
        }
        // 光分
        if (this.rowData.nodeCategory === 'LIGHT_SPLIT') {
          postData.inPortName = this.properties.split.inPortName
          // 名称必填校验
          if (!postData.inPortName) {
            this.$message.error(this.$t('MSG_NOT_EMPTY', { msg: this.$t('PORT_NAME') }))
            return
          }
        }
        // AFS差量
        if (this.rowData.nodeCategory === 'AFS') {
          postData.afsList = []
          const oldList = this.baseData.afsInfo.faceList
          const newList = this.cloneDetailData.afsInfo.faceList
          newList.forEach((face, i) => {
            face.portList.forEach((port, j) => {
              if (port.bizName !== oldList[i].portList[j].bizName) {
                postData.afsList.push({
                  portId: port.portId,
                  bizName: port.bizName
                })
              }
            })
          })
          // 名称必填校验
          if (postData.afsList.some((i) => String(i.bizName).trim() === '')) {
            this.$message.error(this.$t('MSG_NOT_EMPTY', { msg: this.$t('SERVICE_NAME') }))
            return
          }
        }
        console.log('postData', postData)
        nodeApi.updatePortInfo(postData).then((res) => {
          this.$message.success(this.$t('MODIFY_SUCCESS'))
          this.close(true)
        })
      },
      resize() {
        const height = this.$refs.dragDialog.$el.clientHeight
        console.log('resize', this.$refs.dragDialog)
        console.log('resize', height)
        this.$refs.portFlange && this.$refs.portFlange.resize(height)
      },
      close(data) {
        this.baseData = {}
        this.cloneDetailData = null
        this.$emit('close', data)
      },
      // 导入
      importClick(file) {
        importExcel(file).then((res) => {
          console.log(res)
          const properties = deepClone(this.properties)
          if (file.name.includes(this.rowData.nodeName)) {
            this.importData(res.data, properties)
          } else {
            this.$message.error(
              `${this.$t('PLEASE_UPLOAD_NODE')}${this.rowData.nodeName}${this.$t(
                'TEMPLATE_FILE'
              )}`
            )
          }
        })
      },
      importData(data, properties) {
        const formateData = this.datahandle(data)
        console.log('formateData', formateData)
        if (formateData.duplicateValue.length) {
          this.$message.error(
            this.$t('DUPLICATE_PORT_NAME', {
              msg1: this.$t('PORT'),
              msg2: formateData.duplicateValue.join(),
              msg3: this.$t('IMPORT')
            })
          )
          return
        }
        const dataList = formateData.dataList
        if (this.rowData.nodeCategory === 'AFS') {
          const faceList = properties.afsInfo.faceList
          faceList.forEach((obj) => {
            obj.portList.forEach((item) => {
              for (let i = 0; i < dataList.length; i++) {
                const keys = Object.entries(dataList[i])
                if (keys[0][0] === item.portId) {
                  item.bizName = keys[0][1]
                  break
                }
              }
            })
          })
          this.cloneDetailData = {
            ...properties,
            afsInfo: {
              faceList
            }
          }
        } else if (this.rowData.nodeCategory === 'ODF') {
          const faceList = properties.odf.faceList
          faceList.forEach((i) => {
            i.holeList.forEach((j) => {
              for (let i = 0; i < dataList.length; i++) {
                const keys = Object.entries(dataList[i])
                if (keys[0][0] === j.holeId) {
                  j.holeName = keys[0][1]
                  j.installed = keys[1][1] === this.$t('INSTALLED')
                  break
                }
              }
            })
          })
          this.cloneDetailData = {
            ...properties,
            odf: {
              faceList
            }
          }
        } else if (this.rowData.nodeCategory === 'TRANSPORT') {
          const shelfList = properties.trans.shelfList
          // console.log('shelfList', shelfList)
          // console.log('portData', formateData.portData)
          const importPortData = formateData.portData
          shelfList.forEach((i) => {
            i.slotList.forEach((j) => {
              j.netPortList.forEach((z) => {
                if (z.portList[0]) {
                  z.portList[0].bizName = importPortData[z.portList[0].portId].name
                  z.portList[0].resourceCode =
                    importPortData[z.portList[0].portId].sendcode
                }
                if (z.portList[1]) {
                  z.portList[1].bizName = importPortData[z.portList[1].portId].name
                  z.portList[1].resourceCode =
                    importPortData[z.portList[1].portId].receivecode
                }
              })
            })
          })
          this.cloneDetailData = {
            ...properties,
            trans: {
              shelfList
            }
          }
        }
        this.importVisible = false
        // 记录导入日志
        this.addLog({
          api: '/',
          terminal: 'EDIT_PORT_IMPORT', // 导入
          object: this.rowData.nodeName,
          i18nKey: 'EDIT_PORT_IMPORT_LOG',
          deviceName: this.rowData.nodeName,
          operateResult: true
        })
      },
      datahandle(data) {
        const dataList = []
        const allValue = []
        const portData = {}
        const duplicateValue = []
        data.forEach((item) => {
          const values = Object.values(item)
          const val2 = values[2] + ''
          // 查重端口名称
          if (values[1] !== 'ID' && allValue.includes(values[1] + '-' + val2)) {
            duplicateValue.push(val2)
          }
          val2 && allValue.push(values[1] + '-' + val2)
          if (this.rowData.nodeCategory === 'AFS') {
            dataList.push({ [values[1]]: val2 })
          } else if (this.rowData.nodeCategory === 'ODF') {
            dataList.push({ [values[1]]: val2, status: values[3] })
          } else if (this.rowData.nodeCategory === 'TRANSPORT') {
            if (values[4]) {
              const val5 = values[5] + ''
              // 查重端口名称
              if (allValue.includes(values[4] + '-' + val5)) {
                duplicateValue.push(val5)
              }
              val5 && allValue.push(values[4] + '-' + val5)
              portData[values[4]] = {
                sendcode: values[3],
                name: val5,
                receivecode: values[6]
              }
              dataList.push({
                sendcode: values[3],
                [values[4]]: val5,
                receivecode: values[6]
              })
              if (values[7]) {
                const val8 = values[8] + ''
                // 查重端口名称
                if (allValue.includes(values[7] + '-' + val8)) {
                  duplicateValue.push(val8)
                }
                val8 && allValue.push(values[7] + '-' + val8)
                portData[values[7]] = {
                  sendcode: values[3],
                  name: val8,
                  receivecode: values[9]
                }
                dataList.push({
                  sendcode: values[3],
                  [values[7]]: val8,
                  receivecode: values[9]
                })
              }
            } else {
              portData[values[1]] = {
                name: val2,
                sendcode: values[3]
              }
              dataList.push({
                [values[1]]: val2,
                sendcode: values[3]
              })
            }
          }
        })
        return {
          duplicateValue: Array.from(new Set(duplicateValue)),
          dataList: dataList,
          portData: portData
        }
      },
      // 导出文件
      exportClick() {
        try {
          if (this.rowData.nodeCategory === 'AFS') {
            const faceList = this.properties.afsInfo.faceList
            this.exportFn(faceList, 'portList')
          } else if (this.rowData.nodeCategory === 'ODF') {
            const faceList = this.properties.odf.faceList
            this.exportFn(faceList, 'holeList')
          } else if (this.rowData.nodeCategory === 'TRANSPORT') {
            const shelfList = this.properties.trans.shelfList
            this.exportTransFn(shelfList)
          } else if (this.rowData.nodeCategory === 'SPLICE_CLOSURE') {
            tableToExcel(
              'jointable',
              `${this.rowData.nodeName}${this.$t('FEATURE_TYPE_NODE')}${this.$t(
                'PORT_EXPORT'
              )}`
            )
          }
          // 记录导出日志
          this.addLog({
            api: '/',
            terminal: 'EDIT_PORT_EXPORT', // 导出
            object: this.rowData.nodeName,
            i18nKey: 'EDIT_PORT_EXPORT_LOG',
            deviceName: this.rowData.nodeName,
            operateResult: true
          })
        } catch (error) {
          console.log(error)
          // 记录导出日志
          this.addLog({
            api: '/',
            terminal: 'EDIT_PORT_EXPORT', // 导出
            object: this.rowData.nodeName,
            i18nKey: 'EDIT_PORT_EXPORT_LOG',
            deviceName: this.rowData.nodeName,
            operateResult: false
          })
        }
      },
      exportFn(faceList, children) {
        const sheets = []
        const sheetNames = []
        const rowData =
          this.rowData.nodeCategory === 'ODF'
            ? [this.$t('PORT_NUMBER'), 'ID', this.$t('PORT_NAME'), this.$t('PORT_STATUS')]
            : [this.$t('PORT_NUMBER'), 'ID', this.$t('PORT_NAME')]
        faceList.forEach((item) => {
          const arr = []
          item[children].forEach((port, index) => {
            const eq = index + 1
            const num = eq < 10 ? '0' + eq : eq + ''
            const portItem = this.portItemFn(port, num)
            arr.push(portItem)
          })
          //   [this.$t('PORT_NUMBER')]: num,
          //   ID: port.portId,
          //   [this.$t('PORT_NAME')]: port.bizName
          sheets.push([[`${this.rowData.nodeName}-${item.faceName}`], rowData, ...arr])
          sheetNames.push(item.faceName)
        })
        console.log('sheets', sheets)
        const merge = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 2 }}]
        exportExcel(
          sheets,
          `${this.rowData.nodeName}${this.$t('FEATURE_TYPE_NODE')}${this.$t(
            'PORT_EXPORT'
          )}`,
          sheetNames,
          'array',
          merge
        )
      },
      exportTransFn(faceList) {
        // 传输类 单/双芯导出
        const sheets = []
        const sheetNames = []
        faceList.forEach((i) => {
          i.slotList.forEach((j) => {
            const arr = []
            j.netPortList.forEach((z, index) => {
              const eq = index + 1
              const num = eq < 10 ? '0' + eq : eq + ''
              let portItem = {}
              if (z['portList'].length > 1) {
                portItem = {
                  [this.$t('PORT_NUMBER')]: num,
                  [this.$t('SEND_PORT_ID')]: z['portList'][0]['portId'],
                  [this.$t('OUTGOING_PORT')]: z['portList'][0]['bizName'],
                  [this.$t('SENDING_CODE')]: z['portList'][0]['resourceCode'],
                  [this.$t('RECEIVE_PORT_ID')]: z['portList'][1]['portId'],
                  [this.$t('RECEIVING_PORT')]: z['portList'][1]['bizName'],
                  [this.$t('RECEIVING_CODE')]: z['portList'][1]['resourceCode']
                }
              }
              if (z['portList'].length === 1) {
                portItem = {
                  [this.$t('PORT_NUMBER')]: num,
                  ID: z['portList'][0]['portId'],
                  [this.$t('PORT_NAME')]: z['portList'][0]['bizName'],
                  [this.$t('SERVICE_CODE')]: z['portList'][0]['resourceCode']
                }
              }
              arr.push(portItem)
            })
            sheets.push(arr)
            sheetNames.push(`${i.shelfName}-${j.slotName}`)
          })
        })
        exportExcel(
          sheets,
          `${this.rowData.nodeName}${this.$t('FEATURE_TYPE_NODE')}${this.$t(
            'PORT_EXPORT'
          )}`,
          sheetNames
        )
      },
      portItemFn(port, num) {
        if (this.rowData.nodeCategory === 'ODF') {
          return [
            num,
            port.holeId,
            port.holeName,
            port.installed ? this.$t('INSTALLED') : this.$t('UNINSTALLED')
          ]
        } else if (this.rowData.nodeCategory === 'AFS') {
          return [num, port.portId, port.bizName]
        }
      },
      addLog(logData) {
        const obj = {
          ...logData,
          item: 'MENU_NODE_MANAGER', // 节点管理
          realName: this.getUser.realName,
          content: JSON.stringify({
            deviceName: logData.deviceName,
            currentUserId: this.getUserId,
            i18nKey: logData.i18nKey
          })
        }
        // 记录导出日志
        OperateLogApi.addLog(obj)
      }
    }
  }
</script>
<style scoped lang="scss">
@import "src/assets/css/mixin.module";
.node-name {
  width: 100%;
  background-color: #fff;
  color: #fff;
  padding: 5px 10px;
  @include themeify {
    background: themed("bgOtherColor");
    color: themed("textColor");
  }
}
.port-edit-content {
  padding-top: 10px;
  flex: 1;
  overflow: auto;
}
.port-edit {
  ::v-deep .el-dialog__body {
    display: flex;
    flex-direction: column;
  }
}
</style>
